<template>
  <div class="edit-outfit">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="$router.back()" type="text">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>编辑搭配</h2>
      </div>
      <div class="header-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </div>
    </div>

    <div class="edit-content" v-loading="loading">
      <el-row :gutter="20">
        <!-- 左侧：搭配信息 -->
        <el-col :span="12">
          <el-card title="搭配信息">
            <el-form :model="outfitForm" :rules="rules" ref="outfitFormRef" label-width="80px">
              <el-form-item label="搭配名称" prop="name">
                <el-input v-model="outfitForm.name" placeholder="请输入搭配名称" />
              </el-form-item>

              <el-form-item label="描述">
                <el-input
                  v-model="outfitForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入搭配描述"
                />
              </el-form-item>

              <el-form-item label="风格">
                <el-select v-model="outfitForm.style" placeholder="选择风格" clearable>
                  <el-option label="休闲" value="casual" />
                  <el-option label="正式" value="formal" />
                  <el-option label="商务" value="business" />
                  <el-option label="运动" value="sport" />
                  <el-option label="派对" value="party" />
                  <el-option label="复古" value="vintage" />
                  <el-option label="街头" value="street" />
                </el-select>
              </el-form-item>

              <el-form-item label="季节">
                <el-select v-model="outfitForm.season" placeholder="选择季节" clearable>
                  <el-option label="春季" value="spring" />
                  <el-option label="夏季" value="summer" />
                  <el-option label="秋季" value="autumn" />
                  <el-option label="冬季" value="winter" />
                  <el-option label="四季" value="all" />
                </el-select>
              </el-form-item>

              <el-form-item label="评分">
                <el-rate v-model="outfitForm.rating" show-score text-color="#ff9900" />
              </el-form-item>

              <el-form-item label="收藏">
                <el-switch v-model="outfitForm.is_favorite" />
              </el-form-item>

              <el-form-item label="备注">
                <el-input
                  v-model="outfitForm.notes"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧：衣服选择 -->
        <el-col :span="12">
          <el-card title="包含的衣服">
            <div class="selected-clothes">
              <div
                v-for="clothing in selectedClothes"
                :key="clothing.id"
                class="clothing-item"
              >
                <el-image
                  :src="clothing.main_image || '/placeholder.jpg'"
                  fit="cover"
                  class="clothing-image"
                />
                <div class="clothing-info">
                  <div class="clothing-name">{{ clothing.name }}</div>
                  <div class="clothing-category">{{ clothing.category?.name }}</div>
                </div>
                <el-button
                  size="small"
                  type="danger"
                  @click="removeClothing(clothing.id)"
                >
                  移除
                </el-button>
              </div>
            </div>

            <el-button @click="showClothingSelector = true" type="primary" class="add-clothing-btn">
              <el-icon><Plus /></el-icon>
              添加衣服
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 衣服选择对话框 -->
    <el-dialog
      v-model="showClothingSelector"
      title="选择衣服"
      width="80%"
      :before-close="handleCloseSelector"
    >
      <div class="clothing-selector">
        <!-- 搜索和筛选 -->
        <div class="selector-filters">
          <el-input
            v-model="clothingSearch"
            placeholder="搜索衣服..."
            clearable
            @input="loadClothingList"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 衣服列表 -->
        <div class="clothing-grid" v-loading="clothingLoading">
          <div
            v-for="clothing in availableClothes"
            :key="clothing.id"
            class="clothing-card"
            :class="{ selected: isClothingSelected(clothing.id) }"
            @click="toggleClothing(clothing)"
          >
            <el-image
              :src="clothing.main_image || '/placeholder.jpg'"
              fit="cover"
              class="card-image"
            />
            <div class="card-content">
              <div class="clothing-name">{{ clothing.name }}</div>
              <div class="clothing-category">{{ clothing.category?.name }}</div>
            </div>
            <div class="selection-indicator" v-if="isClothingSelected(clothing.id)">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="showClothingSelector = false">取消</el-button>
        <el-button type="primary" @click="confirmClothingSelection">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { outfitAPI, clothingAPI } from '@/api'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const showClothingSelector = ref(false)
const clothingLoading = ref(false)
const clothingSearch = ref('')

const outfitFormRef = ref()
const outfitForm = ref({
  name: '',
  description: '',
  style: '',
  season: '',
  rating: 0,
  is_favorite: false,
  notes: ''
})

const selectedClothes = ref([])
const availableClothes = ref([])
const tempSelectedClothes = ref([])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入搭配名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const outfitId = computed(() => route.params.id)

// 方法
const loadOutfitDetail = async () => {
  loading.value = true
  try {
    const response = await outfitAPI.getDetail(outfitId.value)
    const outfit = response.data

    // 填充表单数据
    outfitForm.value = {
      name: outfit.name,
      description: outfit.description || '',
      style: outfit.style || '',
      season: outfit.season || '',
      rating: outfit.rating || 0,
      is_favorite: outfit.is_favorite || false,
      notes: outfit.notes || ''
    }

    // 设置已选择的衣服
    selectedClothes.value = outfit.clothes || []
  } catch (error) {
    console.error('加载搭配详情失败:', error)
    ElMessage.error('加载搭配详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

const loadClothingList = async () => {
  clothingLoading.value = true
  try {
    const response = await clothingAPI.getList({
      keyword: clothingSearch.value,
      page: 1,
      pageSize: 50
    })
    availableClothes.value = response.data.list || []
  } catch (error) {
    console.error('加载衣服列表失败:', error)
    ElMessage.error('加载衣服列表失败')
  } finally {
    clothingLoading.value = false
  }
}

const isClothingSelected = (clothingId) => {
  return tempSelectedClothes.value.some(c => c.id === clothingId)
}

const toggleClothing = (clothing) => {
  const index = tempSelectedClothes.value.findIndex(c => c.id === clothing.id)
  if (index > -1) {
    tempSelectedClothes.value.splice(index, 1)
  } else {
    tempSelectedClothes.value.push(clothing)
  }
}

const removeClothing = (clothingId) => {
  const index = selectedClothes.value.findIndex(c => c.id === clothingId)
  if (index > -1) {
    selectedClothes.value.splice(index, 1)
  }
}

const handleCloseSelector = () => {
  tempSelectedClothes.value = [...selectedClothes.value]
  showClothingSelector.value = false
}

const confirmClothingSelection = () => {
  selectedClothes.value = [...tempSelectedClothes.value]
  showClothingSelector.value = false
}

const handleCancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的更改将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.back()
  }).catch(() => {
    // 用户取消
  })
}

const handleSave = async () => {
  try {
    await outfitFormRef.value.validate()

    saving.value = true

    const updateData = {
      ...outfitForm.value,
      clothing_ids: selectedClothes.value.map(c => c.id)
    }

    await outfitAPI.update(outfitId.value, updateData)

    ElMessage.success('搭配更新成功')
    router.back()
  } catch (error) {
    if (error.errors) {
      // 表单验证错误
      return
    }
    console.error('保存搭配失败:', error)
    ElMessage.error('保存搭配失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadOutfitDetail()
  loadClothingList()
  tempSelectedClothes.value = [...selectedClothes.value]
})
</script>

<style scoped>
.edit-outfit {
  width: 100%;
  height: 100%;
  padding: 0;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.edit-content {
  min-height: 500px;
}

.selected-clothes {
  margin-bottom: 15px;
}

.clothing-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 10px;
}

.clothing-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.clothing-info {
  flex: 1;
}

.clothing-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.clothing-category {
  font-size: 12px;
  color: #909399;
}

.add-clothing-btn {
  width: 100%;
}

.clothing-selector {
  max-height: 60vh;
  overflow-y: auto;
}

.selector-filters {
  margin-bottom: 20px;
}

.clothing-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.clothing-card {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.clothing-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.clothing-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.card-image {
  width: 100%;
  height: 80px;
}

.card-content {
  padding: 8px;
}

.card-content .clothing-name {
  font-size: 12px;
  margin-bottom: 2px;
}

.card-content .clothing-category {
  font-size: 10px;
}

.selection-indicator {
  position: absolute;
  top: 5px;
  right: 5px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}
</style>
